from rest_framework import generics, status, permissions, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Avg, Count, Q
from .models import Category, Tag, Book, BookImage, BookReview
from .serializers import (
    CategorySerializer, TagSerializer, BookListSerializer,
    BookDetailSerializer, BookCreateUpdateSerializer,
    BookReviewSerializer, BookReviewAdminSerializer
)
from .filters import BookFilter


class CategoryListView(generics.ListAPIView):
    queryset = Category.objects.filter(is_active=True)
    serializer_class = CategorySerializer
    permission_classes = [permissions.AllowAny]


class TagListView(generics.ListAPIView):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [permissions.AllowAny]


class BookListView(generics.ListAPIView):
    queryset = Book.objects.filter(is_active=True).annotate(
        average_rating=Avg('reviews__rating'),
        review_count=Count('reviews', filter=Q(reviews__is_approved=True))
    )
    serializer_class = BookListSerializer
    permission_classes = [permissions.AllowAny]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = BookFilter
    search_fields = ['title', 'author', 'publisher', 'isbn', 'description']
    ordering_fields = ['price', 'created_at', 'average_rating', 'review_count']
    ordering = ['-created_at']


class BookDetailView(generics.RetrieveAPIView):
    queryset = Book.objects.filter(is_active=True).annotate(
        average_rating=Avg('reviews__rating'),
        review_count=Count('reviews', filter=Q(reviews__is_approved=True))
    )
    serializer_class = BookDetailSerializer
    permission_classes = [permissions.AllowAny]
    lookup_field = 'slug'


class BookCreateView(generics.CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookCreateUpdateSerializer
    permission_classes = [permissions.IsAdminUser]


class BookUpdateView(generics.UpdateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookCreateUpdateSerializer
    permission_classes = [permissions.IsAdminUser]
    lookup_field = 'slug'


class BookDeleteView(generics.DestroyAPIView):
    queryset = Book.objects.all()
    permission_classes = [permissions.IsAdminUser]
    lookup_field = 'slug'


class BookReviewListView(generics.ListAPIView):
    serializer_class = BookReviewSerializer
    permission_classes = [permissions.AllowAny]
    
    def get_queryset(self):
        book_slug = self.kwargs['book_slug']
        return BookReview.objects.filter(
            book__slug=book_slug,
            is_approved=True
        ).order_by('-created_at')


class BookReviewCreateView(generics.CreateAPIView):
    queryset = BookReview.objects.all()
    serializer_class = BookReviewSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        book_slug = self.kwargs['book_slug']
        try:
            book = Book.objects.get(slug=book_slug)
        except Book.DoesNotExist:
            return Response(
                {'error': '图书不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 检查用户是否已经评论过
        if BookReview.objects.filter(book=book, user=request.user).exists():
            return Response(
                {'error': '您已经评论过这本书'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(book=book, user=request.user)
        
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class BookReviewAdminListView(generics.ListAPIView):
    queryset = BookReview.objects.all()
    serializer_class = BookReviewAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['book__title', 'user__email', 'title', 'content']
    ordering_fields = ['created_at', 'rating', 'is_approved']
    ordering = ['-created_at']


class BookReviewApproveView(generics.UpdateAPIView):
    queryset = BookReview.objects.all()
    serializer_class = BookReviewAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def patch(self, request, *args, **kwargs):
        review = self.get_object()
        review.is_approved = request.data.get('is_approved', True)
        review.approved_by = request.user
        review.save()
        
        return Response({
            'message': '评论状态已更新',
            'is_approved': review.is_approved
        })


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def book_helpful_vote(request, review_id):
    try:
        review = BookReview.objects.get(id=review_id)
    except BookReview.DoesNotExist:
        return Response(
            {'error': '评论不存在'}, 
            status=status.HTTP_404_NOT_FOUND
        )
    
    vote_type = request.data.get('vote_type')
    
    if vote_type == 'helpful':
        review.helpful_count += 1
    elif vote_type == 'unhelpful':
        review.unhelpful_count += 1
    else:
        return Response(
            {'error': '无效的投票类型'}, 
            status=status.HTTP_400_BAD_REQUEST
        )
    
    review.save()
    
    return Response({
        'helpful_count': review.helpful_count,
        'unhelpful_count': review.unhelpful_count
    })


@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def featured_books(request):
    books = Book.objects.filter(
        is_active=True,
        is_featured=True
    ).annotate(
        average_rating=Avg('reviews__rating'),
        review_count=Count('reviews', filter=Q(reviews__is_approved=True))
    )[:10]
    
    serializer = BookListSerializer(books, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def related_books(request, book_slug):
    try:
        book = Book.objects.get(slug=book_slug)
    except Book.DoesNotExist:
        return Response(
            {'error': '图书不存在'}, 
            status=status.HTTP_404_NOT_FOUND
        )
    
    # 获取相同分类的图书
    related_books = Book.objects.filter(
        categories__in=book.categories.all(),
        is_active=True
    ).exclude(
        id=book.id
    ).annotate(
        average_rating=Avg('reviews__rating'),
        review_count=Count('reviews', filter=Q(reviews__is_approved=True))
    )[:6]
    
    serializer = BookListSerializer(related_books, many=True)
    return Response(serializer.data)
